package handler

import (
	"file-master/cache"
	"file-master/modler"
	"file-master/pkg"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}

	redis_list_red := "list_username" + username
	count, _ := cache.Rdb.Get(cache.Ctx, redis_list_red).Int()

	if count >= 3 {
		c.JSON(200, gin.H{
			"mas":  "密码错误3次",
			"code": 500,
		})
		return
	}

	var user modler.User
	err := modler.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "用户查询失败",
			"code": 500,
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"mas":  "用户不存在",
			"code": 500,
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_list_red)
		if count == 2 {
			cache.Rdb.Set(cache.Ctx, redis_list_red, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"mas":  "密码错误3次,封禁2小时",
				"code": 500,
			})
			return
		}
		c.JSON(200, gin.H{
			"mas":  "密码错误",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "密码正确",
		"code": 200,
	})
	return

}
